package com.jy.appmarket.activity;

import it.gmariotti.cardslib.library.view.CardView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.jy.app.market.idata.card.CardApkRecommend;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.adapter.DownloadMrgAdapter;
import com.jy.appmarket.adapter.DownloadMrgAdapter.DLMrgAdapterClickListener;
import com.jy.appmarket.cards.ApkRecommendUICard;
import com.jy.appmarket.dialog.TextDialog;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadDatabase;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.utils.ApkRecommendHolder;
import com.jy.appmarket.utils.LogUtil;
import com.umeng.analytics.MobclickAgent;

public class DownloadManagerActivity extends DownloadActivity implements DLMrgAdapterClickListener {

	private static String TAG = "DownloadManagerActivity";
	private static final int EXPAND_NO = 2;

	private List<DownloadItem> mOrgDlData = null;
	private Map<String, DownloadItem> mMapDlData = null;
	private List<DownloadItemUI> mUiDlData = null;

	private List<DownloadItem> mUnfinshDLData = null;
	private List<DownloadItem> mFinshDLData = null;

	private boolean mIsExpand = false;

	private DownloadMrgAdapter mListAdapter = null;
	private ListView mListView = null;

	private TextDialog mDeleteDialog = null;
	private View mNoDataView = null;
	private int mNoDataViewHeight = 0;
	private Handler mHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dl_mrg_layout);
		mListView = findViewById(R.id.dl_task_listview);
		mDeleteDialog = new TextDialog(this);
		mNoDataView = LayoutInflater.from(this).inflate(R.layout.dl_mrg_no_data_view, mListView,
				false);
		mListView.addHeaderView(mNoDataView, null, false);
		initTitle();
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				addRecommend();
			}
		}, 200);
		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ApkRecommendHolder.getInstance().updateRecommend(this);
	}

	private void addRecommend() {
		CardApkRecommend car = ApkRecommendHolder.getInstance().getRecommend();
		if (car == null) {
			return;
		}
		View footer = LayoutInflater.from(this).inflate(R.layout.download_manager_footer,
				mListView, false);
		CardView cv = footer.findViewById(R.id.download_manager_footer_cardview);
		ApkRecommendUICard card = new ApkRecommendUICard(this, car);
		//card.setApkSource(new ApkSource("recommend"));
		card.setApkSource(new ApkSource("recommend", null, null, "downloadmanager"));
		cv.setCard(card);
		addFileListener(card);
		mListView.addFooterView(footer, null, false);
	}

	@Override
	protected void onFileDownloadServiceConnected(DownloadService service) {
		loadDlData(mIsExpand);
		initUi();
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(getResources().getString(R.string.download_task));
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	public static class DownloadItemUI {

		public static int DL_FINISH = 0;
		public static int DL_UNFINISH = 1;
		public static int UNFINISH_SECTION = 2;
		public static int FINISH_SECTION = 3;
		public static int SHOW_ALL_FINISH = 4;

		public DownloadItem dlItem;
		public int uiType;
		public Object data;
	}

	private void loadDlData(boolean isExpand) {
		mOrgDlData = getAllDownloadsOrderBy(DownloadDatabase.COL_CREATE_TIME, true);
		if (mOrgDlData == null) {
			LogUtil.e(TAG, "mOrgDlData is null");
			return;
		}

		mMapDlData = new HashMap<String, DownloadItem>();
		mUiDlData = new ArrayList<DownloadItemUI>();

		if (mOrgDlData.size() == 0) {
			LogUtil.i(TAG, "no data in mOrgDlData");
			return;
		}

		mUnfinshDLData = new ArrayList<DownloadItem>();
		mFinshDLData = new ArrayList<DownloadItem>();

		for (DownloadItem di : mOrgDlData) {
			int status = getDownloadStatus(di.getId(), di.getPkgName(), di.getVersionCode());

			if (status == DownloadService.STATUS_INSTALLED
					&& di.getPkgName().equals(getPackageName())) {
				continue;
			}

			if (status == DownloadService.STATUS_INSTALLED) {
				mFinshDLData.add(di);
			} else {
				mUnfinshDLData.add(di);
			}

			mMapDlData.put(di.getId(), di);
		}

		if (mUnfinshDLData.size() != 0) {
			DownloadItemUI ui = new DownloadItemUI();
			ui.uiType = DownloadItemUI.UNFINISH_SECTION;
			ui.data = new Integer(mUnfinshDLData.size());
			mUiDlData.add(ui);

			for (DownloadItem di : mUnfinshDLData) {
				DownloadItemUI uiUnFinish = new DownloadItemUI();
				uiUnFinish.uiType = DownloadItemUI.DL_UNFINISH;
				uiUnFinish.dlItem = di;
				mUiDlData.add(uiUnFinish);
			}
		}

		if (mFinshDLData.size() != 0) {
			DownloadItemUI ui = new DownloadItemUI();
			ui.uiType = DownloadItemUI.FINISH_SECTION;
			ui.data = new Integer(mFinshDLData.size());
			mUiDlData.add(ui);

			int count = 0;
			for (DownloadItem di : mFinshDLData) {
				DownloadItemUI uifinish = new DownloadItemUI();
				uifinish.uiType = DownloadItemUI.DL_FINISH;
				uifinish.dlItem = di;
				mUiDlData.add(uifinish);
				count++;

				if (count == EXPAND_NO && mFinshDLData.size() > EXPAND_NO && !isExpand) {
					DownloadItemUI expand = new DownloadItemUI();
					expand.uiType = DownloadItemUI.SHOW_ALL_FINISH;
					mUiDlData.add(expand);
					break;
				}
			}
		}
	}

	private void initUi() {
		mNoDataViewHeight = (mNoDataView.getHeight() == 0) ? 9999 : mNoDataView.getHeight();
		if (mOrgDlData.size() == 0) {
			mNoDataView.setPadding(0, 0, 0, 0);
		} else {
			mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
		}

		mListAdapter = new DownloadMrgAdapter(this, this);
		mListAdapter.setList(mUiDlData);
		mListView.setAdapter(mListAdapter);
	}

	@Override
	protected void onPackageInstalled(String pkgName) {
		if (mDeleteDialog.isShowing()) {
			mDeleteDialog.cancel();
		}

		loadDlData(mIsExpand);
		if (mOrgDlData.size() == 0) {
			mNoDataView.setPadding(0, 0, 0, 0);
		} else {
			mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
		}

		if (mListAdapter == null) {
			mListAdapter = new DownloadMrgAdapter(this, this);
			mListAdapter.setList(mUiDlData);
			mListView.setAdapter(mListAdapter);
		} else {
			mListAdapter.setList(mUiDlData);
			mListAdapter.notifyDataSetChanged();
		}
		super.onPackageInstalled(pkgName);
	}

	@Override
	protected void onPackageUninstalled(String pkgName) {
		if (mDeleteDialog.isShowing()) {
			mDeleteDialog.cancel();
		}

		loadDlData(mIsExpand);
		if (mOrgDlData.size() == 0) {
			mNoDataView.setPadding(0, 0, 0, 0);
		} else {
			mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
		}
		if (mListAdapter == null) {
			mListAdapter = new DownloadMrgAdapter(this, this);
			mListAdapter.setList(mUiDlData);
			mListView.setAdapter(mListAdapter);
		} else {
			mListAdapter.setList(mUiDlData);
			mListAdapter.notifyDataSetChanged();
		}
		super.onPackageUninstalled(pkgName);
	}

	@Override
	public void onProgressChanged(String id, long downloadedBytes, long speed) {
		if (mOrgDlData == null || mOrgDlData.size() == 0 || mListAdapter == null
				|| mMapDlData == null) {
			return;
		}

		DownloadItem di = mMapDlData.get(id);
		if (di == null) {
			return;
		}

		di.setDownloadedSize(downloadedBytes);
		di.setSpeed(speed);

		mListAdapter.notifyDataSetChanged();
		super.onProgressChanged(id, downloadedBytes, speed);
	}

	@Override
	public void onDownloadCreated(DownloadItem di) {

		if (mDeleteDialog.isShowing()) {
			mDeleteDialog.cancel();
		}

		loadDlData(mIsExpand);
		if (mOrgDlData.size() == 0) {
			mNoDataView.setPadding(0, 0, 0, 0);
		} else {
			mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
		}
		if (mListAdapter == null) {
			mListAdapter = new DownloadMrgAdapter(this, this);
			mListAdapter.setList(mUiDlData);
			mListView.setAdapter(mListAdapter);
		} else {
			mListAdapter.setList(mUiDlData);
			mListAdapter.notifyDataSetChanged();
		}

		super.onDownloadCreated(di);
	}

	@Override
	public void onDownloadChanged(DownloadItem di) {

		// service在addwifi中也调用该接口 ?? 兼容错误
		DownloadItem mapdi = null;
		if (mMapDlData == null || (mapdi = mMapDlData.get(di.getId())) == null) {
			if (mDeleteDialog.isShowing()) {
				mDeleteDialog.cancel();
			}
			loadDlData(mIsExpand);
			if (mOrgDlData.size() == 0) {
				mNoDataView.setPadding(0, 0, 0, 0);
			} else {
				mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
			}
			if (mListAdapter == null) {
				mListAdapter = new DownloadMrgAdapter(this, this);
				mListAdapter.setList(mUiDlData);
				mListView.setAdapter(mListAdapter);
			} else {
				mListAdapter.setList(mUiDlData);
				mListAdapter.notifyDataSetChanged();
			}
			return;
		}

		int sdi = getDownloadStatus(di.getId(), di.getPkgName(), di.getVersionCode());
		int smdi = getDownloadStatus(mapdi.getId(), mapdi.getPkgName(), mapdi.getVersionCode());
		if ((sdi == DownloadService.STATUS_INSTALLED && smdi != DownloadService.STATUS_INSTALLED)
				|| (sdi != DownloadService.STATUS_INSTALLED && smdi == DownloadService.STATUS_INSTALLED)) {
			// 出现了"处理中"和"完成"之间的状态互换，需要重新加载数据 (实际测试，貌似安装完成后，不会走到这里)

			if (mDeleteDialog.isShowing()) {
				mDeleteDialog.cancel();
			}

			loadDlData(mIsExpand);
			if (mOrgDlData.size() == 0) {
				mNoDataView.setPadding(0, 0, 0, 0);
			} else {
				mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
			}
			if (mListAdapter == null) {
				mListAdapter = new DownloadMrgAdapter(this, this);
				mListAdapter.setList(mUiDlData);
				mListView.setAdapter(mListAdapter);
			} else {
				mListAdapter.setList(mUiDlData);
				mListAdapter.notifyDataSetChanged();
			}

		} else {
			// 其余状态之间的转变不会引起 mUiDlData 数据的顺序或数据项个数的转变，因此修改内存状态即可
			mapdi.assignValue(di);
			mListAdapter.notifyDataSetChanged();
		}
		super.onDownloadChanged(di);
	}

	@Override
	public void onDownloadRemoved(String id) {

		if (mDeleteDialog.isShowing()) {
			mDeleteDialog.cancel();
		}

		loadDlData(mIsExpand);
		if (mOrgDlData.size() == 0) {
			mNoDataView.setPadding(0, 0, 0, 0);
		} else {
			mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
		}
		if (mListAdapter == null) {
			mListAdapter = new DownloadMrgAdapter(this, this);
			mListAdapter.setList(mUiDlData);
			mListView.setAdapter(mListAdapter);
		} else {
			mListAdapter.setList(mUiDlData);
			mListAdapter.notifyDataSetChanged();
		}
		super.onDownloadRemoved(id);
	}

	@Override
	public void onExpandClick() {
		mIsExpand = true;
		loadDlData(mIsExpand);
		if (mOrgDlData.size() == 0) {
			mNoDataView.setPadding(0, 0, 0, 0);
		} else {
			mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
		}
		if (mListAdapter == null) {
			mListAdapter = new DownloadMrgAdapter(this, this);
			mListAdapter.setList(mUiDlData);
			mListView.setAdapter(mListAdapter);
		} else {
			mListAdapter.setList(mUiDlData);
			mListAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onAppOpenClick(DownloadItem di) {
		openApp(di.getPkgName());
	}

	@Override
	public void onDealingBtnClick(DownloadItem di) {
		int status = getDownloadStatus(di.getId(), di.getPkgName(), di.getVersionCode());
		switch (status) {
		// case DownloadService.STATUS_NO_STATUS://"无";
		// case DownloadService.STATUS_INSTALLING: //"安装中";
		// case DownloadService.STATUS_INSTALLED: //"已安装";
		// case DownloadService.STATUS_DOWNLOAD_FINISHED: // "下载完成";
		case DownloadService.STATUS_PREPARE_TO_DOWNLOAD: // "准备下载";
		case DownloadService.STATUS_PREPARE_TO_STOP: // "准备停止";
			// do nothing...
			break;

		case DownloadService.STATUS_PENDING: // "排队中";
		case DownloadService.STATUS_DOWNLOADING: // "下载中";
			stopDownload(di.getId());
			break;

		case DownloadService.STATUS_PAUSED_BY_USER: // "用户暂停";
		case DownloadService.STATUS_PAUSED_BY_ERROR: // "下载出错";
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK: // "移动网络等待";
			startDownload(di.getId());
			if (DownloadUtils.isMobileNetwork(this)) {
				Toast.makeText(this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
			}
			break;

		case DownloadService.STATUS_CAN_INSTALL: // "准备安装";
			installApk(di);
			break;

		default:
			break;
		}

	}

	@Override
	public void onDeleteOneDlItem(final DownloadItem di) {
		if (mDeleteDialog.isShowing()) {
			return;
		}

		mDeleteDialog.showTitle(R.string.delete_task).setContent(R.string.delete_task_tip)
				.showButton1(getString(R.string.cancel), new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						mDeleteDialog.cancel();
					}
				}).showButton2(getString(R.string.confirm), new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						removeDownload(di.getId());
						mDeleteDialog.cancel();
					}
				}).show();

	}

	@Override
	public void onClearAllFinishTask() {
		if (mDeleteDialog.isShowing()) {
			mDeleteDialog.cancel();
		}

		clearAllInstallDlTask();

		// reload datas
		loadDlData(mIsExpand);
		if (mOrgDlData.size() == 0) {
			mNoDataView.setPadding(0, 0, 0, 0);
		} else {
			mNoDataView.setPadding(0, -1 * mNoDataViewHeight, 0, 0);
		}
		if (mListAdapter == null) {
			mListAdapter = new DownloadMrgAdapter(this, this);
			mListAdapter.setList(mUiDlData);
			mListView.setAdapter(mListAdapter);
		} else {
			mListAdapter.setList(mUiDlData);
			mListAdapter.notifyDataSetChanged();
		}

	}

	public boolean clearAllInstallDlTask() {
		List<DownloadItem> diList = getAllDownloadsOrderBy(DownloadDatabase.COL_CREATE_TIME, true);
		if (diList == null || diList.size() == 0) {
			LogUtil.e(TAG, "diList is null or empty");
			return false;
		}

		List<String> idList = new ArrayList<String>();
		for (DownloadItem di : diList) {
			int status = getDownloadStatus(di.getId(), di.getPkgName(), di.getVersionCode());

			if (status == DownloadService.STATUS_INSTALLED) {
				idList.add(di.getId());
			}
		}

		return (removeAllInstalled(idList) > 0);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void goBack() {
		AppMarketApplication app = (AppMarketApplication) getApplication();
		if (app.isAppRunning()) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setClass(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			startActivity(intent);
		} else {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}
		finish();
	}
}
